package com.dash.dashrecoder;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
//import android.graphics.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;

public class MainActivity extends Activity {

	private Button startOrStopRecordButton = null;
	private Button showRecordListButton = null;
	
	private Camera myCamera = null;
	private SurfaceView mySurfaceView= null;
	//Video Recoder
	private MediaRecorder myMediaRecorder = null;
	private boolean isRecording = false;
	//isCamerCreate
	private boolean isCameraCreate = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //full screen and no titile
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
        		WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.activity_main);
        
        startOrStopRecordButton = (Button)findViewById(R.id.button_startorstop);
        showRecordListButton = (Button)findViewById(R.id.button_showrecordlist);
        
        showRecordListButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, RecordListActivity.class);
				startActivity(intent);
			}
		});
        
        startOrStopRecordButton.setText("start record");
        startOrStopRecordButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!isRecording){
					releaseMyCamera();
					if(!initMediaRecoder()){
						System.out.println("initMediaRecoder fail!");
					}
					myMediaRecorder.start();
					isRecording = true;
					startOrStopRecordButton.setText("stop record");
				}
				else {
					myMediaRecorder.stop();
					releaseMyMediaRecoder();
					startOrStopRecordButton.setText("start record");
					isRecording = false;
				}
			}
		});
        
        //Test code ...
        //init camera
        if(isCameraCanUse()){
        	if(initCamera()) {
            	System.out.println("open camera successfully");
            }
        	isCameraCreate = true;
            mySurfaceView = new CameraView(this, myCamera);
            mySurfaceView.setKeepScreenOn(true);
            FrameLayout frameLayout = (FrameLayout)findViewById(R.id.CameraView);
            frameLayout.addView(mySurfaceView);
        }
        
        else{
        	finish();
        }
        //Test code..
    }
    
    /* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		 //resume camera
		 /*if(isCameraCanUse()){
	        	if(initCamera()) {
	            	System.out.println("resume camera successfully");
	            }
	            mySurfaceView = new CameraView(this, myCamera);
	            mySurfaceView.setKeepScreenOn(true);
	            FrameLayout frameLayout = (FrameLayout)findViewById(R.id.CameraView);
	            frameLayout.addView(mySurfaceView);
	     }*/
		if(!isCameraCreate){
			if(isCameraCanUse()){
	        	if(initCamera()) {
	            	System.out.println("resume camera successfully");
	            }
	        	isCameraCreate = true;
	            mySurfaceView = new CameraView(this, myCamera);
	            mySurfaceView.setKeepScreenOn(true);
	            FrameLayout frameLayout = (FrameLayout)findViewById(R.id.CameraView);
	            frameLayout.addView(mySurfaceView);
			}
		}
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mySurfaceView = null;
		releaseMyMediaRecoder();
		releaseMyCamera();
		isCameraCreate = false;
	}
    
    /* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		releaseMyMediaRecoder();
		releaseMyCamera();
		

	}
    
    //release MeditaRecoder
    private void releaseMyMediaRecoder() {
    	if(myMediaRecorder != null) {
    		myMediaRecorder.reset();
    		myMediaRecorder.release();
    		myMediaRecorder = null;
    		myCamera.lock();
    	}
    }
    //init MediaRecoder
    private boolean initMediaRecoder() {
    	initCamera();
		myMediaRecorder = new MediaRecorder();

		myCamera.unlock();
		myMediaRecorder.setCamera(myCamera);

		myMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		myMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
		myMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
		//设置recoder的分辨率
		myMediaRecorder.setVideoSize(1280, 720);
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		//录像文件的存储路径
		String filePath = "/mnt/sdcard/Movies" + File.separator + "_" + timeStamp + ".mp4";
		myMediaRecorder.setOutputFile(filePath); 
		myMediaRecorder.setPreviewDisplay(mySurfaceView.getHolder().getSurface());

		try {
			myMediaRecorder.prepare();
		} catch (IllegalStateException e) {
			releaseMyMediaRecoder();
			return false;
		} catch (IOException e) {
			releaseMyMediaRecoder();
			return false;
		}
		return true;
    }
    //release camera
    private void releaseMyCamera() {
    	if(myCamera != null) {
    		myCamera.release();
    		myCamera = null;
    	}
    	isCameraCreate = false;
    }
   
    //judge if the camera is used by others
    public static boolean isCameraCanUse() { 
        boolean canUse = true; 
        Camera mCamera = null; 
        try { 
            // TODO camera�����ҵ�,����?? 
            mCamera = Camera.open(); 
        } catch (Exception e) { 
            canUse = false; 
        } 
        if (canUse) { 
            mCamera.release(); 
            mCamera = null; 
        } 
         
        return canUse; 
    } 	
    //init camera
    private boolean initCamera(){
    	if(myCamera==null){
    		myCamera = Camera.open();
        	//show camera Vertical
//        	myCamera.setDisplayOrientation(90);
    		//set resolution 1280*720
    		// ��ȡ���������������Ҫ��������ȱʡ         
    		Camera.Parameters parameters = myCamera.getParameters(); 
    		// ������Ƭ��ʽ 
    		//parameters.setPictureFormat(PixelFormat.JPEG); 
    		// ����Ԥ䯳ߴ�ע��Ҫ����֧�ַ�Χ��ѡ�� 
    		parameters.setPreviewSize(1280, 720); 
    		// ������Ƭ����ע��Ҫ����֧�ַ�Χ��ѡ�� 
    		parameters.setPictureSize(1280, 720); 
    		// ������������� 
    		myCamera.setParameters(parameters);  
    		// ʼ���� 
    		myCamera.startPreview();
    		// end set resolution 1280*720
    	}  
    	if(myCamera!=null){
    		return true;
    	}
    	return false;
    }
    
    private class CameraView extends SurfaceView implements SurfaceHolder.Callback {

    	private SurfaceHolder mHolder;
    	private Camera mCamera;
		public CameraView(Context context, Camera camera) {
			super(context);
			// TODO Auto-generated constructor stub
			this.mCamera = camera;
			mHolder = getHolder();
			mHolder.addCallback(this);
			mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			try {
				mCamera.setPreviewDisplay(holder);
				mCamera.startPreview();

			} catch (Exception e) {
			}
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			// TODO Auto-generated method stub
			if (mHolder.getSurface() == null) {
				// preview surface does not exist
				return;
			}

			// stop preview before making changes
			try {
				mCamera.stopPreview();
			} catch (Exception e) {
				// ignore: tried to stop a non-existent preview
			}

			// make any resize, rotate or reformatting changes here

			// start preview with new settings
			try {
				mCamera.setPreviewDisplay(mHolder);
				mCamera.startPreview();

			} catch (Exception e) {
			}
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			
		}
    	
    }
}
